package com.example.blackbox.Fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.example.blackbox.Activity.CollectionActivity;
import com.example.blackbox.Activity.MineInfoActivity;
import com.example.blackbox.Activity.SettingActivity;
import com.example.blackbox.Adapter.GameAdapter;
import com.example.blackbox.Broadcast.MineBroadcast;
import com.example.blackbox.Data.Game;
import com.example.blackbox.Data.JsonTool;
import com.example.blackbox.Net.NetTool;
import com.example.blackbox.R;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;

public class MineFragment extends Fragment {
    View view;
    ListView gameLV;
    ArrayList<Game> games=new ArrayList<>();
    LinearLayout mineLL,collection;
    ImageView head,setting,camera;
    TextView name,autograph,collections;
    SharedPreferences sp;
    Handler handler;
    String data;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.fragment_mine,null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initUI();


        handler=new Handler(){
            @Override
            public void handleMessage( Message msg) {
                ArrayList<Game> game = JsonTool.getGame(data);
                GameAdapter adapter=new GameAdapter(game,getActivity());
                gameLV.setAdapter(adapter);
                setListViewHeight(gameLV);
            }
        };


        new Thread(new Runnable() {
            @Override
            public void run() {
                data=NetTool.getJsonString("http://10.0.2.2:8080/androids/json/game.json");
                Message m=handler.obtainMessage();
                handler.sendMessage(m);
            }
        }).start();



        mineLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), MineInfoActivity.class));
            }
        });



        String names=sp.getString("name",null);
        String autographs=sp.getString("autograph",null);
        String img=sp.getString("img",null);
        //sp.edit().putString("collections","10").commit();
        collections.setText(sp.getString("collections","0"));
        if (!TextUtils.isEmpty(names)){
            name.setText(names);
            autograph.setText(autographs);

            try{
                    byte[] byteArray= Base64.decode(img, Base64.DEFAULT);
                    if(byteArray.length!=0){
                        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(byteArray);
                        Bitmap bitmap= BitmapFactory.decodeStream(byteArrayInputStream);
                        head.setImageBitmap(bitmap);
                    }
                }catch (Exception e){
                    e.printStackTrace();
            }

        }


        IntentFilter filter=new IntentFilter();
        filter.addAction("MINE_INFO_CHANGES_ACTION");
        filter.addAction("DELETE_NEWS_ACTION");
        MineBroadcast myBroadCastReceiver=new MineBroadcast(getActivity());
        getActivity().registerReceiver(myBroadCastReceiver,filter);

        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), SettingActivity.class));
            }
        });

        collection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!"0".equals(sp.getString("collections","0"))){
                    startActivity(new Intent(getActivity(), CollectionActivity.class));
                }else{
                    Toast.makeText(getActivity(),"对不起您还没有收藏",Toast.LENGTH_SHORT).show();
                }

            }
        });
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tuneUpCamera();
            }
        });

    }

   public void initUI(){
       mineLL=getActivity().findViewById(R.id.mine_ll_mine);
       sp=getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
       name=getActivity().findViewById(R.id.mine_tv_name);
       autograph=getActivity().findViewById(R.id.mine_tv_autograph);
       head=getActivity().findViewById(R.id.mine_iv_head);
       setting=getActivity().findViewById(R.id.mine_iv_setting);
       gameLV=getActivity().findViewById(R.id.mine_ls_game);
       collections=getActivity().findViewById(R.id.mine_tv_collections);
       collection=getActivity().findViewById(R.id.mine_ll_collections);
       camera=getActivity().findViewById(R.id.mine_iv_camera);
   }




    /**
     * 动态设置ListView的高度
     * @param listView
     */
    public static void setListViewHeight(ListView listView) {
        if(listView == null) return;
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     * 打开相机
     */
    public void tuneUpCamera(){
        if (checkReadPermission(Manifest.permission.CAMERA,0010)){
            Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent,0011);
        }
    }

    public boolean checkReadPermission(String string_permission,int request_code) {
        boolean flag = false;
        if (ContextCompat.checkSelfPermission(getActivity(), string_permission) == PackageManager.PERMISSION_GRANTED) {//已有权限
            flag = true;
        } else {//申请权限
            ActivityCompat.requestPermissions(getActivity(), new String[]{string_permission}, request_code);
        }
        return flag;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissions.length != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {//失败
            Toast.makeText(getActivity(),"请允许相机权限后再试", Toast.LENGTH_SHORT).show();
        } else {//成功
            tuneUpCamera();
        }
    }
}
